import React from 'react'
import Star from './star'
import PropTypes from 'prop-types'

export default class Rate extends React.Component {
  constructor(props) {
    super(props)

    let value = props.value;
    if (value === undefined) {
      value = props.defaultValue;
    }
    this.state = {
      value
    }
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      let value = nextProps.value;
      if (value === undefined) {
        value = nextProps.defaultValue;
      }
      this.setState({
        value,
      });
    }
  }
  
    _onClick = (index) => {
        this.setState({
            value: index
        });
        this.props.onChange(index);
    }
 
    render() {
        let stars = [];

        for (let i = 0, len = this.props.count; i < len; i++) {
          let index = len - i;
    
          stars.push(
            <Star
              key={'star-' + i}
              index={index}
              active={this.state.value == index}
              onClick={this._onClick}
              disabled={this.props.disabled}
            />
          );
        }

          return (
            <div className="bt">
              {stars}
            </div>
          );
    }
}

Rate.defaultProps = {
    count: 5,
    defaultValue: 0,
    disabled: false,
}

Rate.propTypes = {
  count: PropTypes.number,
  defaultValue: PropTypes.number,
  disabled: PropTypes.bool,
  onChange: PropTypes.func,
}

